package cn.ybz21.hibot.util;

import com.ibm.micro.client.mqttv3.MqttClient;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;

/**
 * MQTTV3的发布消息类
 */
public class MQTTPublisher {
	public static void postMessage(String strTopic, String strMsg) {
		try {
			MqttClient client = new MqttClient(StaticValues.IP_MQTT_SERVER,
					"mqttserver-pub");
			MqttTopic topic = client.getTopic(strTopic);
			MqttMessage message = new MqttMessage(strMsg.getBytes());
			message.setQos(1);
			client.connect();
			// MqttDeliveryToken token = topic.publish(message);
			topic.publish(message);
			// while (!token.isComplete()) {
			// token.waitForCompletion(1000);
			// }
			if (client.isConnected())
				client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void postFile(String strTopic, String filePath) {
		try {
			MqttClient client = new MqttClient(StaticValues.IP_MQTT_SERVER,
					"mqttserver-pub");
			MqttTopic topic = client.getTopic(strTopic);
			MqttMessage message = new MqttMessage(
					FileUtil.toByteArray(filePath));
			message.setQos(1);
			client.connect();
			// MqttDeliveryToken token = topic.publish(message);
			topic.publish(message);
			// while (!token.isComplete()) {
			// token.waitForCompletion(1000);
			// }
			if (client.isConnected())
				client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// public static void main(String args[]) {
	// postMessage("sensor", "test1111");
	// }
	
}
